<template>
  <div class="login-container">
    <div class="login-background">
      <div class="water-animation"></div>
    </div>

    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <el-icon size="40" color="#409EFF"><WaterIcon /></el-icon>
          <h1>水云鉴</h1>
        </div>
        <p class="subtitle">水利质检系统</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="captcha" v-if="showCaptcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              :prefix-icon="Picture"
              clearable
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaImage" alt="验证码" />
              <div class="refresh-hint">点击刷新</div>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <p>© 2024 水云鉴水利质检系统. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Setting as WaterIcon,
  User,
  Lock,
  Picture
} from '@element-plus/icons-vue'
import { login } from '../servers/user'

const router = useRouter()

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 是否显示验证码
const showCaptcha = ref(false)

// 验证码图片
const captchaImage = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 调用登录API
    const response = await login({
      username: loginForm.username,
      password: loginForm.password,
      captcha: loginForm.captcha,
      rememberMe: loginForm.rememberMe
    })

    // 根据axios返回结构，code为200表示成功
    if (response.code == 200) {
      ElMessage.success('登录成功！')

      // 保存用户信息到本地存储
      const userInfo = {
        username: loginForm.username,
        token: response.data?.token || 'mock-token-' + Date.now(),
        role: 'admin',
        avatar: 'https://via.placeholder.com/40x40/409EFF/FFFFFF?text=' + loginForm.username.charAt(0).toUpperCase()
      }

      if (loginForm.rememberMe) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      } else {
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
      }

      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(response.msg || response.message || '登录失败，请检查用户名和密码')

      // 登录失败3次后显示验证码
      if (response.showCaptcha) {
        showCaptcha.value = true
        refreshCaptcha()
      }
    }
  } catch (error) {
    console.error('登录错误:', error)

    // 如果是网络错误或API不存在，使用模拟登录
    const errorMessage = error.message || error.toString()
    if (errorMessage.includes('网络连接失败') || errorMessage.includes('请求失败') || errorMessage.includes('timeout')) {
      console.log('使用模拟登录')

      // 模拟登录成功
      ElMessage.success('登录成功！')

      // 保存用户信息到本地存储
      const userInfo = {
        username: loginForm.username,
        token: 'mock-token-' + Date.now(),
        role: 'admin',
        avatar: 'https://via.placeholder.com/40x40/409EFF/FFFFFF?text=' + loginForm.username.charAt(0).toUpperCase()
      }

      if (loginForm.rememberMe) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      } else {
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
      }

      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error('登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  // 这里应该调用获取验证码的API
  // 暂时使用随机生成的验证码图片URL
  captchaImage.value = `https://via.placeholder.com/120x40/409EFF/FFFFFF?text=${Math.random().toString(36).substr(2, 4).toUpperCase()}`
}

// 组件挂载时的处理
onMounted(() => {
  // 检查是否已经登录
  const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
  if (userInfo) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.water-animation {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 200px;
  background: linear-gradient(45deg, rgba(64, 158, 255, 0.1), rgba(64, 158, 255, 0.3));
  animation: wave 3s ease-in-out infinite;
}

@keyframes wave {
  0%, 100% {
    transform: translateX(0) scaleY(1);
  }
  50% {
    transform: translateX(-25px) scaleY(1.1);
  }
}

.login-card {
  position: relative;
  z-index: 10;
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.logo h1 {
  margin-left: 12px;
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  border-radius: 8px;
}

.login-form .el-input__wrapper {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-image {
  position: relative;
  cursor: pointer;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.captcha-image img {
  width: 120px;
  height: 40px;
  display: block;
}

.refresh-hint {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 10px;
  text-align: center;
  padding: 2px;
  opacity: 0;
  transition: opacity 0.3s;
}

.captcha-image:hover .refresh-hint {
  opacity: 1;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 45px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #409EFF, #67C23A);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-footer p {
  color: #999;
  font-size: 12px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 30px 20px;
    margin: 20px;
  }

  .logo h1 {
    font-size: 24px;
  }

  .captcha-container {
    flex-direction: column;
    align-items: stretch;
  }

  .captcha-image {
    align-self: center;
  }
}

/* 输入框聚焦效果 */
.login-form .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 按钮加载状态 */
.login-button.is-loading {
  background: linear-gradient(135deg, #a0cfff, #95d475);
}
</style>
